/*
 * 刷新间隔(20分钟)
 */
var REFRESH_TIME = 1200000;
/**
 * 定位操作
 */
var LocationUtil = {};
/**
 * 地球长轴(单位M)
 * @type {number}
 */
var EARTH_RADIUS = 6378137.0;
/**
 * π
 * @type {number}
 */
var PI = Math.PI;
/**
 * 角度转弧度
 * @param {Number} d 角度
 * @returns {Number} 弧度
 */
var getRad = function (d) {
    return d * PI / 180.0;
};
/**
 * 开始刷新地址
 * @public
 */
LocationUtil.startRefreshAddress = function () {
    if (window.inReview) {
        return;
    }
    LocationUtil.refreshAddress();
    // cc.log('开始刷新地址');
    setTimeout(LocationUtil.startRefreshAddress, REFRESH_TIME);
};

/**
 * 刷新地址
 * @private
 */
LocationUtil.refreshAddress = function () {
    if (!cc.sys.isNative) {
        return;
    }
    if (LocationUtil.isStart) {
        return;
    }
    if (cc.sys.os === cc.sys.OS_IOS && window.nativeVersion >= '3.0.0') {
        LocationManager.requestLocation();
    } else {
        LocationUtil.clearLocation();
        LocationUtil.start();
        if (LocationUtil.waitLocationInterval != null) {
            clearInterval(LocationUtil.waitLocationInterval);
            LocationUtil.waitLocationInterval = null;
        }
        LocationUtil.waitLocationInterval = setInterval(LocationUtil.waitLocation.bind(this), 1000);
    }
    LocationUtil.isStart = true;
};

/**
 * 等待地址回调
 * @private
 */
LocationUtil.waitLocation = function () {
    var locationStr = LocationUtil.getLocation();
    if (isNullString(locationStr)) {
        return;
    }
    if (LocationUtil.waitLocationInterval == null) {
        return;
    }
    LocationUtil.isStart = false;
    clearInterval(LocationUtil.waitLocationInterval);
    var parts = locationStr.split(',');
    if (parts.length != 2) {
        return;
    }
    // ios版本的经纬度和android相反
    if (cc.sys.os == cc.sys.OS_IOS) {
        LocationUtil.longitude = parseFloat(parts[0]);
        LocationUtil.latitude = parseFloat(parts[1]);
    } else if (cc.sys.os == cc.sys.OS_ANDROID) {
        LocationUtil.latitude = parseFloat(parts[0]);
        LocationUtil.longitude = parseFloat(parts[1]);
    }
    LocationUtil.requestAddress();
};

/**
 * 清除获得的地址
 * @private
 */
LocationUtil.clearLocation = function () {
    if (window.inReview) return;
    if (cc.sys.os == cc.sys.OS_IOS) {
        jsb.reflection.callStaticMethod('LocationManager', 'clearCurLocation');
    } else if (cc.sys.os == cc.sys.OS_ANDROID) {
        jsb.reflection.callStaticMethod(packageUri + '/utils/LocationManager', 'clearCurLocation', '()V');
    }
};
/**
 * 取得当前的地址(经纬度)
 * @returns {String}
 * @private
 */
LocationUtil.getLocation = function () {
    if (window.inReview) {
        return null;
    }
    if (cc.sys.os == cc.sys.OS_IOS) {
        return jsb.reflection.callStaticMethod('LocationManager', 'getCurLocation');
    } else if (cc.sys.os == cc.sys.OS_ANDROID) {
        return jsb.reflection.callStaticMethod(packageUri + '/utils/LocationManager', 'getCurLocation', '()Ljava/lang/String;');
    }
};

/**
 * 开始
 */
LocationUtil.init = function () {
    if (window.inReview) {
        return;
    }
    if (window.fristIn && !PermissionUtil.hasPermission(PermissionType.Location)) {
        PermissionUtil.requestPermission(PermissionType.Location);
    }
};
/**
 * 开始监听
 */
LocationUtil.start = function () {
    if (window.inReview) {
        return;
    }
    LocationUtil.fristStart = true;
    if (cc.sys.os == cc.sys.OS_IOS) {
        jsb.reflection.callStaticMethod('LocationManager', 'startLocation');
    } else if (cc.sys.os == cc.sys.OS_ANDROID) {
        jsb.reflection.callStaticMethod(packageUri + '/utils/LocationManager', 'startLocation', '()V');
    }
};
/**
 * 停止监听
 */
LocationUtil.stop = function () {
    if (window.inReview) {
        return;
    }
    if (cc.sys.os == cc.sys.OS_IOS) {
        jsb.reflection.callStaticMethod("LocationUtil", "stop");
    } else if (cc.sys.os == cc.sys.OS_ANDROID) {
        jsb.reflection.callStaticMethod(packageUri + "/utils/LocationUtil", "stop", "()V");
    }
};

/**
 * 请求地址
 */
LocationUtil.requestAddress = function () {
    if (window.inReview) return;
    var coordtype = 'wgs84ll';
    if (cc.sys.os == cc.sys.OS_ANDROID) {
        var address = jsb.reflection.callStaticMethod(packageUri + '/utils/LocationManager', 'getCurLocationInfo', '()Ljava/lang/String;');
        if (isNullString(address)) {
            return;
        }
        LocationUtil.address = address;
        gameData.locationInfo = address;
        cc.log('请求地址信息成功!');
        network.send(3007, {
            location: LocationUtil.latitude + ',' + LocationUtil.longitude,
            locationCN: LocationUtil.address
        });
        return;
    }
    /**
     * 定位改为从配置地址获取，未配置则用原来逻辑
     * ditu 为需要使用的访问地址
     * ditu2 为显示用 逻辑中不涉及
     */
    var locHttp = gameData.opt_conf_2.ditu;
    if (locHttp && _.isString(locHttp) && locHttp.indexOf('http') >= 0) {
        var requestUrl = locHttp + '?' + 'location=' + LocationUtil.latitude + ',' + LocationUtil.longitude;
        LocationUtil.requestBaidu(requestUrl);
    } else {
        var requestUrl = 'http://api.map.baidu.com/geocoder/v2/?callback=renderReverse';
        requestUrl += '&coordtype=' + coordtype;
        requestUrl += '&location=' + LocationUtil.latitude + ',' + LocationUtil.longitude;
        requestUrl += '&output=json';
        requestUrl += '&pois=0&ak=' + LocationUtil.randomKey();
        LocationUtil.requestBaidu(requestUrl);
    }
};
/**
 * 取得具体地点
 * @param {String}locStr
 */
LocationUtil.getLocationInfo = function (locStr) {
    if (window.inReview) {
        return;
    }
    if (isNullString(locStr)) {
        return;
    }
    if (!LocationUtil.fristStart) {
        return;
    }
    gameData.location = locStr;
    var coordtype = 'wgs84ll';
    if (cc.sys.os == cc.sys.OS_ANDROID) {
        coordtype = 'bd09ll';
        LocationUtil.stop();
    }
    if (LocationUtil.requestInterval) {
        clearInterval(LocationUtil.requestInterval);
        LocationUtil.requestInterval = null;
    }
    LocationUtil.requestInterval = setInterval(LocationUtil.requestBaidu.bind(this, coordtype, locStr), 100);

};

/**
 * 发送百度地址请求
 * @param requestUrl
 */
LocationUtil.requestBaidu = function (requestUrl) {
    http.get(requestUrl,
        function (str) {
            try {
                str = str.substring(29, str.length - 1);
                var jsonData = JSON.parse(str);
                var status = jsonData.status;
                if (status == 0) {
                    var locationInfo = jsonData.result['formatted_address'];
                    var lng = jsonData.result.location['lng']; //经度 北京116.46
                    var lat = jsonData.result.location['lat']; //纬度 北京39.92
                    if (lng)
                        gameData.location = lat + ',' + lng;
                    if (!isNullString(locationInfo)) {
                        gameData.locationInfo = locationInfo;
                        var sendData = {};
                        sendData.location = gameData.location;
                        sendData.locationCN = gameData.locationInfo;
                        network.send(MsgCode.RefreshPlayersLoc, sendData);
                    }
                    cc.log(gameData.location);
                    cc.log(gameData.locationInfo);
                }

            } catch (e) {

            }
            ;
        },
        function () {
        },
        {'Accept-Encoding': 'deflate'}
    );
};

LocationUtil.randomKey = function () {
    var id = Math.round(Math.random() * 3);
    var KEYS = [
        'WIVhGkuCRHrD57PnqK3hqZYpMjgavx9p',
        'Y8XAbnM0mhXYURWjX7EUer999wONTdRl',
        'haB8XTt53xh5uIZoAwEhYAAZVUrLhDWy',
        'NKOlWy6PxCWBXyoxT93LZhAVvw7UkPFZ'
    ];
    if (id < 0 || id >= KEYS.length) {
        id = 0;
    }
    return KEYS[id];
};

/**
 * approx distance between two points on earth ellipsoid
 * @param lat1
 * @param lng1
 * @param lat2
 * @param lng2
 * @returns {Number} distance
 */
LocationUtil.getFlatternDistance = function (lat1, lng1, lat2, lng2) {
    lat1 = parseFloat(lat1);
    lng1 = parseFloat(lng1);
    lat2 = parseFloat(lat2);
    lng2 = parseFloat(lng2);
    var f = getRad((lat1 + lat2) / 2);
    var g = getRad((lat1 - lat2) / 2);
    var l = getRad((lng1 - lng2) / 2);

    var sg = Math.sin(g);
    var sl = Math.sin(l);
    var sf = Math.sin(f);

    var s, c, w, r, d, h1, h2;
    var a = EARTH_RADIUS;
    var fl = 1 / 298.257;

    sg = sg * sg;
    sl = sl * sl;
    sf = sf * sf;

    s = sg * (1 - sl) + (1 - sf) * sl;
    c = (1 - sg) * (1 - sl) + sf * sl;

    w = Math.atan(Math.sqrt(s / c));
    r = Math.sqrt(s * c) / w;
    d = 2 * w * a;
    h1 = (3 * r - 1) / 2 / c;
    h2 = (3 * r + 1) / 2 / s;

    var ret = d * (1 + fl * (h1 * sf * (1 - sg) - h2 * (1 - sf) * sg));
    return _.isNaN(ret) ? 0 : ret.toFixed(1);
};